package com.example.api;


import com.example.pojo.User;
import com.example.service.UserService;
import com.example.util.Response;
import com.example.util.ResponseResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.List;
/**
 * Description:
 * Param:
 * return:
 * Author:20201003095余方圆*
 * Date:2022/12/24
 */

@RestController
@Api(tags = "管理员登录管理接口")
public class UserLoginAPI {
    @Autowired
    UserService userService;

    //登录接口 url:
    @PostMapping("/login")
    @ApiOperation("登录管理员")
    public ResponseResult<Object> login(String login_admin_name, String login_admin_password){

        //1.获取当前的 Subject. 调用 SecurityUtils.getSubject();
        Subject subject = SecurityUtils.getSubject();
        //2.创建登录令牌,存储了用户名和密码，这个token是shiro创建的，也可以使用 jwt token
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(login_admin_name,login_admin_password);
        System.out.println("token:"+usernamePasswordToken);
        //3.登录判断
        try {
            // 3.1调用shiro的login方法进行登录判断
            subject.login(usernamePasswordToken);
            //将token返回给前端
//            msg=Msg.success("登录成功").add("token",subject.getSession().getId());
            userService.saveToken(login_admin_name,subject.getSession().getId().toString());
            return Response.createOkResp("登录成功" ,subject.getSession().getId());

        } catch (Exception  e) {
//            msg = Msg.fail("账号出错或密码出错");
            return Response.createFailResp("账号出错或密码出错");
        }
    }

    //需要权限为 user:create才能访问/index
    @ApiOperation(" user:create才能访问/index")
    @RequiresPermissions("user:create")
    @GetMapping("/index")
    public ResponseResult<Object> index(@RequestHeader String token){
        return Response.createOkResp("访问成功");
    }

    //需要权限ROLE_ADMIN才能访问hello
    @ApiOperation("需要权限ROLE_ADMIN才能访问hello")
    @RequiresPermissions("user:update")
    @GetMapping("/hello")
    public ResponseResult<Object> hello(@RequestHeader String token){
        return Response.createOkResp("访问成功");
    }

    //@RequiresPermissions注解：权限控制
    @ApiOperation("权限控制")
    @RequiresPermissions("user:list")
    @GetMapping("list")
    public ResponseResult<Object> list(Model model){
        List<User> users = userService.findUsers();
        return Response.createOkResp("访问成功");
    }

    @ApiOperation("管理员注册")
    @PostMapping("/register")
    public ResponseResult<Object> register(String username, String password) {
        System.out.print(username);
        User user= new User();
        //加密的次数
        int hashIterations = 2;
        //盐值这里的salt是 username+salt（一般是用户名加一个随机字符串）, 这里以字符串“long”为例)
        String salt = "aaa";
        // 加密方式
        String hashAlgorithmName = "MD5";
        //加密
        Object simpleHash = new SimpleHash(hashAlgorithmName, password, salt, hashIterations);
        user.setAdmin_name(username);
        user.setAdmin_password(simpleHash.toString());
        user.setSalt(salt);
        System.out.println(user);
        userService.saveUser_row(username,password);
        userService.saveUser(username,simpleHash.toString(),salt);
        return Response.createOkResp("添加管理员成功");

    }


    //注销接口
    @ApiOperation("管理员退出账号")
    @PostMapping("/logout")
    public ResponseResult<Object> logout(@RequestHeader("token")String token){
        Subject subject = SecurityUtils.getSubject();
        //退出
        subject.logout();
        return Response.createOkResp("注销成功");
    }
}

